
angular.module('ibosApp.controllers', [])

  .controller('LoginCtrl', function ($scope, $state, Settings, User, $location, $window) {
    var oaurlKey = 'oa_h5_url',
      oausername = 'oa_h5_username',
      oauserpass = 'oa_h5_userpass'

    var oldusername = localStorage.getItem(oausername)
    $scope.user = {
      oaurl: localStorage.getItem(oaurlKey),
      username: localStorage.getItem(oausername),
      password: localStorage.getItem(oauserpass)
    };

    if (localStorage.getItem(oaurlKey) != ''
     && localStorage.getItem(oausername) != '' 
      && localStorage.getItem(oauserpass) != '' 
      && localStorage.getItem(oaurlKey) != undefined
      && localStorage.getItem(oausername) != undefined
      && localStorage.getItem(oauserpass) != undefined) {
        doLogin(); //自动登录
    }
    $scope.submitLogin = doLogin;

    // function getCookieByKey(key) {
    //   var cookies = document.cookie.split('; '), url = '';
    //   for(var i=0; i < cookies.length; i++) {
    //     var values = cookies[i].split('=')
    //     if (values[0] === key) {
    //       url = values[1]
    //       break;
    //     }
    //   }
    //   return url
    // }
    function checkIsHttp(url) {
      var temp = 'http://'
      var http = url.slice(0, 7)
      if (http == temp) return url
      return temp + url
    }
    function doLogin() {
      var data = $scope.user, oaurl = data.oaurl
      if (oaurl == '' || oaurl == undefined) { //为空就默认演示站
        oaurl = 'http://demo.ibos.com.cn/';
      }
      oaurl = checkIsHttp(oaurl)
      Settings.hostUrl = oaurl
      Settings.rootUrl = oaurl + '?r=mobile';

      $scope.logining = true;
      User.login(data)
        .success(function (res) {
          localStorage.setItem(oaurlKey, oaurl);
          localStorage.setItem(oausername, data.username);
          localStorage.setItem(oauserpass, data.password);
          res.login && $location.path(Settings.mainState).replace(); //$state.go(Settings.mainState); //直接使用当前页替换，不跳转，避免存在history中
          if (data.username != oldusername) { //换账号登录了，刷新以清缓存
            $window.location.reload();
          }
        })
        .finally(function () {
          $scope.logining = false;
          $scope.user.password = '';
        });
    };
  })

  // Apps 应用列表页
  .controller('AppsCtrl', function ($scope, $ionicModal, $localstorage, $timeout, $state, Utils, User, Apps, $ionicActionSheet, IbPopup) {
    var LOCAL_SETTINGS_KEY = 'portal.settings';
    var localPortalSettings = $localstorage.getObject(LOCAL_SETTINGS_KEY) || {};

    $scope.apps = Apps.all();
    $scope.user = User.user;

    function orderFilter(key) {
      return function (a, b) {
        var as = localPortalSettings[a.name];
        var bs = localPortalSettings[b.name];

        if (as && typeof as[key] !== 'undefined') {
          if (bs && typeof bs[key] !== 'undefined') {
            return as[key] > bs[key] ? 1 : -1;
          } else {
            return 1;
          }
        }
      };
    }

    $scope.loginOut = function () {
      $scope.hideMore = $ionicActionSheet.show({
        destructiveText: '退出登录',
        cancelText: '取消',
        destructiveButtonClicked: function () {
          IbPopup.confirm({ title: '确认退出登录？' }).then(function (flag) {
            if (flag) {
              localStorage.setItem('oa_h5_userpass', '');
              User.password = '';
              User.logout();
            }
          });
          return true;
        }
      })
    }

    var moduleDisabled = {
      icon: [],
      panel: ['cabinet', 'contacts', 'thread']
    };

    ['icon', 'panel'].forEach(function (value) {
      $scope.settings = $scope.settings || {};

      var ins = $scope.settings[value] = {
        apps: [],

        isDisabled: function (app) {
          return moduleDisabled[value].indexOf(app.name) !== -1;
        },

        getApps: function () {
          this.apps = $scope.apps.filter(this.isShow.bind(this)).sort(orderFilter(value + 'Index'));
          return this.apps;
        },

        // 检查设置模块图标、面板是否在快速入口显示
        // 只有用户明确设置为 false 才不显示，默认则显示
        // 判断 icon、panel 是否显示
        isShow: function (app) {
          if (this.isDisabled(app)) return false;
          if (localPortalSettings && localPortalSettings[app.name] && localPortalSettings[app.name][value] === false) return false;
          return true;
        },

        // 切换 icon、panel 显示状态
        toggleShow: function ($event, app) {
          localPortalSettings[app.name] = localPortalSettings[app.name] || {};
          // 设置 icon、panel 的显示状态
          localPortalSettings[app.name][value] = $event.target.checked;

          // 删除排序序号
          delete localPortalSettings[app.name][value + 'Index'];

          // 保存显示状态到本地
          $localstorage.setObject(LOCAL_SETTINGS_KEY, localPortalSettings);

          this.getApps();
        },

        reorder: function (app, $fromIndex, $toIndex) {
          this.apps.splice($fromIndex, 1);
          this.apps.splice($toIndex, 0, app);

          this.apps.forEach(function (app, index) {
            localPortalSettings[app.name] = localPortalSettings[app.name] || {};
            localPortalSettings[app.name][value + 'Index'] = index;
          });

          $localstorage.setObject(LOCAL_SETTINGS_KEY, localPortalSettings);
        },
      };

      ins.getApps();
      $scope.refresh = function () {
        $scope.$broadcast('portal');
        $timeout(function () {
          $scope.$broadcast('scroll.refreshComplete')
        }, 1000);
      };
    });

    // 设置显示/隐藏窗口
    $ionicModal.fromTemplateUrl('templates/portal-setting.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function (modal) {
      $scope.setModal = modal;
      $scope.$on('$destroy', function () {
        modal.remove();
      });
      $scope.$on('$ionicView.leave', function () {
        modal.hide();
      });
    });

    // 排序窗口
    $ionicModal.fromTemplateUrl('templates/portal-order.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function (modal) {
      $scope.orderModal = modal;
      $scope.$on('$destroy', function () {
        modal.remove();
      });
      $scope.$on('$ionicView.leave', function () {
        modal.hide();
      });
    });
  })

  // 工作日志控制器
  .controller('AppsDiaryCtrl', function ($scope, $http, Settings) {
    $scope.personal = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/diary')
          .success(function (res) {
            that.list = res.data || res.datas;
          });
      }
    };

    $scope.review = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/diary/allsubs')
          .success(function (res) {
            that.list = res.data || res.diary;
          });
      }
    };

    $scope.follow = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/diary/attention')
          .success(function (res) {
            that.list = res.data || res.diary;
          });
      }
    };

    $scope.tabOn = '';
    $scope.tab = function (tabName) {
      $scope.tabOn = tabName;

      $scope[tabName].loading = true;
      $scope[tabName].load()
        .finally(function () {
          $scope[tabName].loading = false;
        });
    };

    $scope.tab('personal');

    $scope.$on('portal', function () {
      $scope.tab('personal')
    });
  })

  // 工作流控制器
  .controller('AppsWorkflowCtrl', function ($scope, $http, Settings) {

    $scope.todo = {
      loading: false,
      url: '/work&type=todo'
    };
    $scope.follow = {
      loading: false,
      url: '/work/follow'
    };
    $scope.done = {
      loading: false,
      url: '/work&type=done'
    };

    $scope.tabOn = '';
    $scope.tab = function (tabName) {
      $scope.tabOn = tabName;

      $scope[tabName].loading = true;

      $http.get(Settings.rootUrl + $scope[tabName].url)
        .success(function (res) {
          $scope[tabName].list = res.data || res.datas;
        })
        .finally(function () {
          $scope[tabName].loading = false;
        });
    };

    $scope.tab('todo');
    $scope.$on('portal', function () {
      $scope.tab('todo')
    });
  })

  // 日程控制器
  .controller('AppsCalendarCtrl', function ($scope, $http, Settings, Calendar, CalendarUtil) {
    $scope.calendar = {
      loading: true,
      url: Settings.rootUrl + '/calendar'
    };

    // 初始化控制器时，自动获取数据, 自动获取下月和本月的日程
    function getData() {
      $http.get($scope.calendar.url, {
        params: CalendarUtil.getDateRange(),
      })
        .success(function (data) {
          $scope.calendar.list = CalendarUtil.parseEvents(data.events);
        })
        .finally(function () {
          $scope.calendar.loading = false;
        })
    }
    getData();

    // 判断日程是否跨天
    $scope.isInterDay = function (cal) {
      return cal.endtime - cal.starttime > 86400000;
    };
    $scope.$on('portal', getData);
  })

  // 任务指派控制器
  .controller('AppsAssignmentCtrl', function ($scope, $http, Settings) {

    $scope.unfinished = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/assignmentunfinished')
          .success(function (res) {
            that.list = res.data || res.chargeData;
          });
      }
    };

    $scope.finished = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/assignmentfinished')
          .success(function (res) {
            that.list = res.data || res.datas;

          });
      }
    };

    $scope.tabOn = '';
    $scope.tab = function (tabName) {
      $scope.tabOn = tabName;

      $scope[tabName].loading = true;
      $scope[tabName].load()
        .finally(function () {
          $scope[tabName].loading = false;
        });
    };

    $scope.tab('unfinished');

    // 是否已过期
    $scope.isOverdue = function (item) {
      return item &&
        item.endtime &&
        Date.now() > item.endtime * 1000;
    };

    // 是否设置了提醒
    $scope.haveRemind = function (item) {
      return item &&
        // 过期时不显示提醒
        !$scope.isOverdue(item) &&
        item.remindtime > 0;
    };

    $scope.$on('portal', function () {
      $scope.tab('unfinished')
    });
  })

  // 公文控制器
  .controller('AppsDocsCtrl', function ($scope, $http, Settings) {
    $scope.unsigned = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/docs&type=nosign')
          .success(function (res) {
            that.list = res.data || res.datas;
          });
      }
    };

    $scope.published = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/docs')
          .success(function (res) {
            that.list = res.data || res.datas;
          });
      }
    };

    $scope.tabOn = '';
    $scope.tab = function (tabName) {
      $scope.tabOn = tabName;

      $scope[tabName].loading = true;
      $scope[tabName].load()
        .finally(function () {
          $scope[tabName].loading = false;
        });
    };

    $scope.tab('unsigned');
    $scope.$on('portal', function () {
      $scope.tab('unsigned')
    });
  })

  // 信息中心控制器
  .controller('AppsNewsCtrl', function ($scope, $http, Settings) {
    $scope.unread = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/news&type=new')
          .success(function (res) {
            that.list = res.data || res.datas;
          });
      }
    };

    $scope.published = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/news')
          .success(function (res) {
            that.list = res.data || res.datas;
          });
      }
    };

    $scope.tabOn = '';
    $scope.tab = function (tabName) {
      $scope.tabOn = tabName;

      $scope[tabName].loading = true;
      $scope[tabName].load()
        .finally(function () {
          $scope[tabName].loading = false;
        });
    };

    $scope.tab('unread');
    $scope.$on('portal', function () {
      $scope.tab('unread');
    });
  })

  // 邮件控制器
  .controller('AppsEmailCtrl', function ($scope, $http, Settings) {
    $scope.inbox = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/mail&type=inbox')
          .success(function (res) {
            that.list = res.data || res.datas;
          });
      }
    };

    $scope.todo = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/mail&type=todo')
          .success(function (res) {
            that.list = res.data || res.datas;
          });
      }
    };

    $scope.tabOn = '';
    $scope.tab = function (tabName) {
      $scope.tabOn = tabName;

      $scope[tabName].loading = true;
      $scope[tabName].load()
        .finally(function () {
          $scope[tabName].loading = false;
        });
    };

    $scope.tab('inbox');
    $scope.$on('portal', function () {
      $scope.tab('inbox');
    });
  })

  //活动控制器
  .controller('AppsActivityCtrl', function ($scope, $http, Settings) {
    $scope.activity = {
      loading: false,
      load: function () {
        var that = this;
        return $http.get(Settings.rootUrl + '/activity')
          .success(function (res) {
            that.list = res.data || res.datas;
            console.log(that.list, "活动")
          });
      }
    };

    //$scope.todo = {
    //  url: Settings.rootUrl + '/mail&type=todo',
    //  loading: false,
    //  load: function() {
    //    var that = this;
    //    return $http.get(this.url)
    //      .success(function(res) {
    //        that.list = res.data || res.datas;
    //      });
    //  }
    //};

    $scope.tabOn = '';
    $scope.tab = function (tabName) {
      $scope.tabOn = tabName;

      $scope[tabName].loading = true;
      $scope[tabName].load()
        .finally(function () {
          $scope[tabName].loading = false;
        });
    };

    $scope.tab('inbox');
    $scope.$on('portal', function () {
      $scope.tab('inbox');
    });
  });